import { reqCartList, reqDeleteCart, reqUpdateChecked } from "@/api";

const actions = {
  //  获取购物车列表
  async getCartList({ commit }) {
    let result = await reqCartList();
    if (result.code == 200) {
      console.log(result);
      commit("SETCARTLIST", result.data);
    }
  },

  //  删除购物车商品
  async deleteCart({ commit }, goodsId) {
    let result = await reqDeleteCart(goodsId);
    if (result.code == 200) {
      console.log(result);
      return "success";
    } else {
      return Promise.reject(new Error("failure"));
    }
  },

  // 切换商品选中状态
  async updateIsChecked({ commit }, { goodsId, isChecked }) {
    let result = await reqUpdateChecked(goodsId, isChecked);
    console.log(result);
    if (result.code == 200) {
      console.log(result);
      return "success";
    } else {
      return Promise.reject(new Error("failure"));
    }
  },

  // 删除选中商品
  handlerDeleteChecked({ dispatch, getters }) {
    // 存放要删除的promise对象
    let promiseArr = []
    //利用deleteCart来删除isCheck == 1的商品
    // 遍历购物车商品
    getters.cartInfoList.forEach((item) => {
      //  item.isChecked == 1的话派发给delete接口处理删除事件
      let promise =  //在当前仓库写不用加仓库名
        item.isChecked == 1 ? dispatch("deleteCart", item.skuId) : "";
        promiseArr.push(promise)
    });
    return Promise.all(promiseArr) // promise对象全都未执行reject则返回真
  },

// 全选按钮
  updateCheckedAll({dispatch,getters},isChecked){ //解构context中的state和dispatch
     let promiseArr = [] //临时存放数据
     //遍历caetList
    getters.cartInfoList.forEach((item)=>{
        // 每一项都执行updateIsChecked
        let promise =  dispatch('updateIsChecked',{
            goodsId:item.skuId, 
            isChecked,
        })
       promiseArr.push(promise)
    })
    return Promise.all(promiseArr)
  }  
};
const mutations = {
  SETCARTLIST(state, value) {
    state.cartList = value;
  },
};
const state = {
  cartList: [],
};
const getters = {
  cartInfoList(state) {
    return state.cartList[0].cartInfoList;
  },
};

export default {
  namespaced: true,
  actions,
  mutations,
  state,
  getters,
};
